package main

import (
	"fmt"
	"sort"
)

func main() {
	fmt.Println(maximumSum([]int{18, 43, 36, 13, 7}))
}

func maximumSum(nums []int) int {
	ans := -1
	m := make(map[int][]int)
	for _, num := range nums {
		var sum int
		for x := num; x > 0; x /= 10 {
			sum += x % 10
		}
		if _, ok := m[sum]; ok && len(m[sum]) == 2 {
			if num > m[sum][1] {
				m[sum][1] = num
			} else if num > m[sum][0] {
				m[sum][0] = num
			}
		} else {
			m[sum] = append(m[sum], num)
			if len(m[sum]) == 2 {
				sort.Ints(m[sum])
			}
		}
		if len(m[sum]) == 2 && m[sum][1]+m[sum][0] > ans {
			ans = m[sum][1] + m[sum][0]
		}
	}
	return ans
}
